import javax.swing.*;
import java.awt.*;
import java.util.Random;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

public class game2048 extends JPanel{
    private static final int SIZE = 4;
    private final int[][] grid = new int[SIZE][SIZE];
    private final Random random = new Random();
    private void drawTile(Graphics g,int value,int x, int y){
        int p = (int)((int)Math.log(value)/Math.log(2));
        g.setColor(value == 0 ? Color.LIGHT_GRAY : new Color(255 - p*20,240,200));
        g.fillRect(x,y,100,100);
        g.setColor(Color.BLACK);
        g.fillRect(x,y,100,100);
        if(value != 0){
            String text = String.valueOf(value);
            FontMetrics fm = g.getFontMetrics();
            int w = fm.stringWidth(text);
            int h = fm.getHeight();
            int textX = x + (100 - w)/2; 
            int textY = y + (100 - h)/2+fm.getAscent();
            g.drawString(text,textX,textY);
        }

    }

    private void spawnTile(){
        int x,y;   // 位置
        // 避免数字生成在同一位置
        do{
            x = random.nextInt(SIZE);
            y = random.nextInt(SIZE);
        } while (grid[x][y] !=0);

        grid[x][y] = random.nextInt(10) < 5 ? 2 : 4;
    }
    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0,0,getWidth(),getHeight());
        for(int i=0;i<SIZE;i++){
            for(int j=0;j<SIZE;j++){
                drawTile(g,grid[i][j],j*100,i*100);
            }
        }

    }
    public static void main(String[] args) {
        JFrame frame = new JFrame("2048 game");
        frame.setSize(420,460);
        game2048 game2048 = new game2048();
        frame.add(game2048);
        frame.setVisible(true);
    }
}